package com.iotechn.iot.device.hook;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.iotechn.iot.device.entity.DeviceDo;
import com.iotechn.iot.device.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2018-08-29
 * Time: 下午4:13
 */
@Controller
@RequestMapping("/emq")
public class EMQWebHook {

    @Autowired
    private DeviceMapper deviceMapper;

    @ResponseBody
    @RequestMapping("/hook")
    public String hook(@RequestBody String request) {
        JSONObject jsonObject = JSONObject.parseObject(request);
        String action = jsonObject.getString("action");
        String clientId = jsonObject.getString("client_id");
        DeviceDo deviceDo = new DeviceDo();
        if ("client_connected".equals(action)) {
            deviceDo.setStatus(1);
        } else if ("client_disconnected".equals(action)) {
            deviceDo.setStatus(0);
        }

        deviceMapper.update(deviceDo,
                new EntityWrapper<DeviceDo>()
                        .eq("name",clientId));
        return "";
    }
}
